<template>
  <j-modal :title='title' :width='1200' :visible='visible' :confirmLoading='confirmLoading' switchFullscreen
    @ok='handleOk' @cancel='handleCancel' cancelText='关闭'>
    <a-divider style='font-weight: 600;margin-top: 0px;' orientation='left'>基本信息</a-divider>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-col :md='8' :sm='24'>
          <a-form-item label='选择人员' v-if='!itemShow' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input-search placeholder='请选择协访人员' v-decorator="['parentRealName',validatorRules.parentRealName]"
              :disabled='disableSubmit' readOnly enter-button @search="productSearch2('superiorUser')" />
            <a-input readOnly type='hidden' v-decorator="[ 'parentUserName', {}]" />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='人员职位'>
            <a-input :disabled='true' v-decorator="['positionName']" />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属组织'>
            <a-input :disabled='true' v-decorator="['departName']" />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='循环日期'>
            <a-range-picker :placeholder="['开始时间','结束时间']" :format="'YYYY-MM-DD'" :valueFormat="'YYYY-MM-DD'"
              v-decorator="['dataRange', validatorRules.dataRange]" @change='dateRangeChange'></a-range-picker>
          </a-form-item>
        </a-col>
        <a-divider style='font-weight: 400;margin-top: 0px;' orientation='left'>拜访信息</a-divider>
        <a-col :md='24' :sm='12'>
         </a-col>
         <a-col :md='8' :sm='24'>
                     <a-form-item
                       :labelCol='labelCol'
                       :wrapperCol='wrapperCol'
                       label='线路组1'
                       >
         <!--              <cn-dict-select-tag-->
         <!--                placeholder='请选择商品分类'-->
         <!--                triggerChange-->
         <!--                :options="{value:'dictDataCode',label:'dictDataDesc'}"-->
         <!--                v-decorator.trim="['userType1']" />-->
                         <a-input-search placeholder='请选择线路组'  v-decorator="[ 'classifytotName',validatorRules.classifytotName]" :disabled='disableSubmit'
                                         readOnly enter-button @search="productSearch('superiorUser')" />
                         <a-input readOnly type='hidden' v-decorator="[ 'classifytotName',validatorRules.classifytotName]" />
                       <!--              <a-input placeholder='请输入' v-decorator="[ 'yw', validatorRules.address]" />-->
                     </a-form-item>
                   </a-col>
         <a-col :md='8' :sm='24'>
                     <a-form-item
                       :labelCol='labelCol'
                       :wrapperCol='wrapperCol'
                       label='线路组2'
                       >
         <!--              <cn-dict-select-tag-->
         <!--                placeholder='请选择商品分类'-->
         <!--                triggerChange-->
         <!--                :options="{value:'dictDataCode',label:'dictDataDesc'}"-->
         <!--                v-decorator.trim="['userType1']" />-->
                         <a-input-search placeholder='请选择线路组'  v-decorator="[ 'classifyName',validatorRules.classifyName]" :disabled='disableSubmit'
                                         readOnly enter-button @search="productSearch1('superiorUser')" />
                         <a-input readOnly type='hidden' v-decorator="[ 'classifyName',validatorRules.classifyName]" />
                       <!--              <a-input placeholder='请输入' v-decorator="[ 'yw', validatorRules.address]" />-->
                     </a-form-item>
                   </a-col>
        <a-col :md='24' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='排除'>
            <a-radio-group v-model="value" @change="onChange">
              <a-radio :value="1">
                星期一
              </a-radio>
              <a-radio :value="2">
                星期二
              </a-radio>
              <a-radio :value="3">
                星期三
              </a-radio>
              <a-radio :value="4">
                星期四
              </a-radio>
              <a-radio :value="5">
                星期五
              </a-radio>
              <a-radio :value="6">
                星期六
              </a-radio>
              <a-radio :value="7">
                星期日
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-button style='margin: 10px 30px 0px 30px;' @click="handleConfigTer(record)" type='primary'
          v-if='!disableSubmit'>新增
        </a-button>
        <!-- <div style='padding: 10px 20px;'>
          <a-table ref='table' size='middle' bordered rowKey='idst' :columns='columns' :dataSource='dataSource'
            :scroll='{x:400,y:240 }' :rowSelection='{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange}'
            @change='handleTableChange'>
            <span slot='action' slot-scope='text, record'>
              <a style='color: red;' @click='handleDelete(record)' v-if='!disableSubmit'>删除</a>
            </span>
          </a-table>
        </div> -->
      </a-form>

    </a-spin>
    <!--    <choose-modal-->
    <!--      ref='chooseModal1'-->
    <!--      :chooseUrl='orgurl'-->
    <!--      :tableFields='orgColumns'-->
    <!--      @choose='okbropro2'-->
    <!--      :removeChildren="true"-->
    <!--      mode='checkbox'-->
    <!--      :searchCondition="[{ label: '人员姓名', field: 'orgCode' },{ label: '人员职位', field: 'orgName' },{ label: '所属组织', field: 'orgName' }]"-->
    <!--    ></choose-modal>-->
    <!-- <proChose ref='prochoose' v-bind='modalProps' @okbro='okbropro'></proChose> -->
    <WedPalnMakingMod modal-width='90%' ref="ConfigPosCust" @okall='dataUserRess'></WedPalnMakingMod>
    <StorePlanMod modal-width='90%' ref="ConfigModal" @ok="saveUserRelation"></StorePlanMod>
    <proChose ref="prochoose" name="商品分类" v-bind='modalProps1' @okbro="okbropro1"></proChose>
    <proChose ref="prochoose1" name="线路组" v-bind='modalProps' @okbro="okbropro"></proChose>
    <proChose ref='prochoose2' v-bind='modalProps' @okbro='okbropro2'></proChose>
  </j-modal>
</template>

<script>
  import {
    httpAction
  } from '@/api/manage'
  import proChose from '@comp/cn-components/ProChose'

  import pick from 'lodash.pick'
  import chooseModal from '@/components/cn-components/ChooseModal'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import WedPalnMakingMod from './WedPalnMakingMod.vue'
  import StorePlanMod from './StorePlanMod.vue'
  export default {
    name: 'SfaSignConfigModal',
    components: {
      JTreeSelect,
      chooseModal,
      proChose,
      WedPalnMakingMod,
      StorePlanMod
    },
    data() {
      return {
        name: '',
        time:'星期一',
        title: '操作',
        objs: [],
        value: 1,
        dataSource: [],
        dataSource2: [],
        visitLineCustomerVos: [],
        visible: false,
        model: {},
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          }
        },
        columns: [{
            title: '职位编号',
            align: 'center',
            dataIndex: 'custCode'
          },
          {
            title: '职位名称',
            align: 'center',
            dataIndex: 'custName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        positionsColumns: [
          // {
          //   title: '#',
          //   key: 'rowIndex',
          //   width: 60,
          //   align: 'center',
          //   customRender: function(t, r, index) {
          //     return parseInt(index) + 1
          //   }
          // },
          {
            title: '门店编码',
            align: 'center',
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: 'center',
            dataIndex: 'terminalName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        productSearch(status) {
          this.$refs.prochoose1.rowKey = 'id'
          let formconfig = [
            {
              key: 'groupCode',
              label: '分类编号'
            },
            {
              key: 'groupName',
              label: '分类名称'
            }
          ]
          let tableconfig = {
            columns: [
              {
                title: '分类编号',
                align: 'left',
                dataIndex: 'groupCode',
                width: 120,
                ellipsis: true
              },
              {
                title: '分类名称',
                align: 'left',
                dataIndex: 'groupName',
                width: 120,
                ellipsis: true
              }
            ],
            list: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitGroupController/findPageList',
            multiple: false,
            columW: 10
          }

          this.name = '用户'
          let dataSource = []
          if (this.form.getFieldValue('superiorUser')) {
            dataSource = [{
              userName: this.form.getFieldValue('superiorUser'),
              realName: this.form.getFieldValue('classifyCode')
            }]
          }
          console.log(dataSource)
          this.$refs.prochoose1.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        },
        productSearch1(status) {
          this.$refs.prochoose.rowKey = 'id'
          let formconfig = [
            {
              key: 'groupCode',
              label: '分类编号'
            },
            {
              key: 'groupName',
              label: '分类名称'
            }
          ]
          let tableconfig = {
            columns: [
              {
                title: '线路编号',
                align: 'left',
                dataIndex: 'groupCode',
                width: 120,
                ellipsis: true
              },
              {
                title: '分类名称',
                align: 'left',
                dataIndex: 'groupName',
                width: 120,
                ellipsis: true
              }
            ],
            list: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitGroupController/findPageList',
            multiple: false,
            columW: 10
          }

          this.name = '用户'
          let dataSource = []
          if (this.form.getFieldValue('superiorUser')) {
            dataSource = [{
              userName: this.form.getFieldValue('superiorUser'),
              realName: this.form.getFieldValue('classifyCode')
            }]
          }
          console.log(dataSource)
          this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        },
        productSearch2(status) {
          this.$refs.prochoose2.rowKey = 'id'
          let formconfig = [{
              key: 'userName',
              label: '用户账户'
            },
            {
              key: 'realName',
              label: '用户名称'
            }
          ]
          let tableconfig = {
            columns: [{
                title: '用户账户',
                align: 'left',
                dataIndex: 'userName',
                width: 120,
                ellipsis: true
              },
              {
                title: '用户名称',
                align: 'left',
                dataIndex: 'realName',
                width: 120,
                ellipsis: true
              }
            ],
            list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

            multiple: false,
            columW: 10
          }

          this.name = '用户'
          let dataSource = []
          if (this.form.getFieldValue('superiorUser')) {
            dataSource = [{
              userName: this.form.getFieldValue('superiorUser'),
              realName: this.form.getFieldValue('realsname')
            }]
          }
          this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        },
        rule: [{
          count: 0,
          actCode: '',
          orderNum: '',
          discount: '',
          gifts: []
        }],
        chara: [],
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          parentRealName: {
            rules: [{
              required: true,
              message: ''
            }]
          },
          classifyName:{
            rules: [{
              required: true,
              message: ''
            }]
          },
          classifytotName:{
            rules: [{
              required: true,
              message: ''
            }]
          },
        },
        url: {
          add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/saveOrUpdateVisit',
          savePosCust: window._CONFIG['domianURL'] + '/cnTerminalExtendController/saveTerminalExtend',
          saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos',
        }
      }
    },
    computed: {
      modalProps() {
        return {
          name: this.name
        }
      },
      modalProps1() {
        return {
          name: this.name
        }
      }
    },
    methods: {
      okbropro1(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        console.log(objs)
        this.form.setFieldsValue({
          classifyName: objs.groupName,

        })
        this.model.classifyCode=objs.groupCode
      },
      okbropro(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        console.log(objs)
        this.form.setFieldsValue({
          classifytotName: objs.groupName,

        })
        this.model.classifyCode=objs.groupCode
      },
      okbropro2(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        this.objs = objs
        this.form.setFieldsValue({
          parentUserName: objs.userName,
          parentRealName: objs.realName,
          positionName: objs.positionName,
          positionCode: objs.positionCode,
          departName: objs.departName,
          departCode: objs.departCode,
        })
      },
      onChange(e) {
        console.log(e.target)
        if(e.target.value==1){
          this.time='星期一'
        }
        if(e.target.value==2){
          this.time='星期二'
        }
        if(e.target.value==3){
          this.time='星期三'
        }
        if(e.target.value==4){
          this.time='星期四'
        }
        if(e.target.value==5){
          this.time='星期五'
        }
        if(e.target.value==6){
          this.time='星期六'
        }
        if(e.target.value==7){
          this.time='星期日'
        }
        // console.log('radio checked', e.target.value);
      },
      saveUserRelation(params) {

        this.dataSource2 = params.cnTerminalVos
        postAction(this.url.saveUserRelation, params).then(async (res) => {
          if (res.success) {
            this.$message.success(res.message)
            await this.loadData()
            this.$refs.ConfigModal.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.ConfigModal.confirmLoading = false
          //that.close();
        })

      },
      handleDelete(record) {
        for (let i = 0; i < this.dataSource2.length; i++) {
          this.dataSource[i].byVisitCode = this.dataSource[i].custCode
          this.dataSource[i].byVisitName = this.dataSource[i].custName
          this.dataSource[i].byVisitType = 1
          if (this.dataSource[i].custCode == record.custCode) {
            this.dataSource.splice(i, 1)
          }
        }
      },
      handleDelete2(record) {

        for (let i = 0; i < this.dataSource2.length; i++) {
          if (this.dataSource2[i].terminalCode == record.terminalCode) {
            this.dataSource2.splice(i, 1)
          }
        }

        // this['dataSource2'].removeByCode(record,'id')
        // this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
        // this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
        // this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
      },
      dataUserRess(params) {
        console.log(111)
        this.dataSource = params.customerExtendVos
      },
      //上级用户选择
      productSearch(status) {
        this.$refs.prochoose.rowKey = 'id'
        let formconfig = [{
            key: 'userName',
            label: '用户账户'
          },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
              title: '用户账户',
              align: 'left',
              dataIndex: 'userName',
              width: 120,
              ellipsis: true
            },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

          multiple: false,
          columW: 10
        }

        this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      //有效期时间
      addInclude() {
        this.$refs.chooseModal1.show()
      },
      add() {
        this.edit({})
      },
      edit(record,id) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.model.isRoll = this.model.isRoll + ''
        this.model.isControl = this.model.isControl + ''
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'jobStatus', 'signOutStart', 'Position',
            'orgCode', 'visitor'))
        })
      },
      handleConfigTer(record, type, modal = 'ConfigPosCust') {
        this.$refs[modal].showModal(record)
        return false
      },
      handleConfig(record, type, modal = 'ConfigModal') {
        this.$refs[modal].showModal(record)
        return false
      },
      async handleWhite(record) {
        this.currentWhite = record
        this.$refs.WhiteModal.showModal(record.terminalCode)
      },
      handelSaveWhite(typeList, productList, positionList, record) {

        let that = this
        const tList = typeList.map(type => Object.assign({
          code: type.code,
          name: type.name,
          dataType: 3
        }))
        const pList = productList.map(type => Object.assign({
          code: type.code,
          name: type.name,
          remarks: type.imgUrl,
          dataType: 4
        }))
        const positions = positionList.map(type => Object.assign({
          code: type.positionCode,
          name: type.positionName,
          dataType: 5
        }))
        if (!record.extendVos) record.extendVos = []
        const retainRows = record.extendVos.filter(row => [1, 2].includes(Number(row.dataType)))
        record.extendVos = [...retainRows, ...tList, ...pList, ...positions]
        that.loadData()
        postAction(window._CONFIG['domianURL'] + '/cnTerminalController/saveTerExtend', record).then(async (res) => {
          if (res.success) {
            that.$message.success(res.message)
            this.$refs.WhiteModal.showModal('')
            this.$refs.WhiteModal.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.WhiteModal.confirmLoading = false
          //that.close();
        })
      },
      savePosCust(params) {

        postAction(this.url.savePosCust, params).then(async (res) => {
          if (res.success) {
            this.$message.success(res.message)
            await this.loadData()
            this.$refs.ConfigPosCust.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.ConfigPosCust.confirmLoading = false
          //that.close();
        })
      },
      close() {

        this.$emit('close')
        this.visible = false
      },

      handleOk() {
        const that = this
        // 触发表单验证
        let dataSource = this.dataSource.map(type => Object.assign({
          byVisitCode: type.custCode,
          byVisitName: type.custName,
          byVisitType: 1
        }))
        let dataSource2 = this.dataSource2.map(type => Object.assign({
          byVisitCode: type.terminalCode,
          byVisitName: type.terminalName,
          byVisitType: 2
        }))
        // console.log(dataSource,dataSource2)
        this.visitLineCustomerVos = dataSource2.concat(dataSource)
        // console.log(this.visitLineCustomerVos)
        this.form.validateFields((err, values) => {
          console.log(values)
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            httpurl += this.url.add
            let method = ''
            method = 'post'
            let formData = Object.assign(this.model, values)
            formData.positionCode = this.objs.positionCode
            formData.departCode = this.objs.departCode
            formData.visitLineCustomerVos = this.visitLineCustomerVos
            formData.timelist=this.time
            console.log(formData)
            //时间格式化
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      }
    }
  }
</script>

<style scoped>

</style>
